﻿using ApplicationModels.A04.Interactions;
using ApplicationModels.A08.Statistics;
using AutoMapper;
using Commons.Helpers;
using Commons.Responses;
using EntityModels.E01.Systems;
using EntityModels.E04.Interactions;
using EntityModels.E08.Statistics;
using IApplicationServices;
using IRepositories;
using Newtonsoft.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ApplicationService
{
    public class LikeService : BaseApplicationService<int, Like, LikeAM>,ILikeService
    {
        private readonly RedisHelper redisHelper;
        private readonly IRabbitMQService _rabbitMQService;
        public LikeService(ILikeRepository repository, IMapper mapper, IRabbitMQService rabbitMQService) : base(repository, mapper)
        {
            redisHelper = new RedisHelper();
            _rabbitMQService = rabbitMQService;
        }
        public override async Task<MessageResponse> AddAsync(LikeAM apiBo)
        {
            try
            {
                //var message = new NotificationMessage
                //{
                //    SenderId = Guid.Parse(apiBo.AppUserId),
                //    ReceiverId = Guid.Parse(apiBo.PhotographAppUserId),
                //    PhotographName = apiBo.PhotographName,
                //    Type = Commons.Enums.NotificationTypeEnum.点赞通知
                //};
                //_rabbitMQService.Publish("notifications_queue", message);
                var redisKey = "";
                var redisValue = "";
                redisKey = "statistics_photograph_" + apiBo.PhotographId;
                redisValue = redisHelper.StringGet(redisKey);
                PhotographStatisticsAM statistic;
                PhotographStatistics sbo;
                if (redisValue == null)
                {
                    sbo = (await Repository.GetOtherAsync<int, PhotographStatistics>(x => x.PhotographId == Guid.Parse(apiBo.PhotographId))).Data;
                    sbo.LikeCount += 1;
                    statistic = Mapper.Map<PhotographStatisticsAM>(sbo);
                    
                    redisValue = JsonConvert.SerializeObject(statistic);
                    redisHelper.StringSet(redisKey, redisValue);
                }
                else
                {
                    statistic = JsonConvert.DeserializeObject<PhotographStatisticsAM>(redisValue);
                    statistic.LikeCount += 1;

                    sbo = Mapper.Map<PhotographStatistics>(statistic);
                    redisValue = JsonConvert.SerializeObject(statistic);
                    redisHelper.StringSet(redisKey, redisValue);
                }
                await Repository.UpdateOtherAsync<int, PhotographStatistics>(sbo);
                return await base.AddAsync(apiBo);
            }catch(Exception e)
            {
                throw new Exception("点赞失败!");
            }
        }
    }
}
